import threading
import time
from time import sleep
import socket
import sys



rate='1'
code=0

def udp(typr):
    global rate
    rate+='1'

    # 1.创建一个udp套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    local_addr = ("", 4000)          #绑定本机端口
    udp_socket.bind(local_addr)

    # 3. 等待接收对方发送的数据
    while(True):
      try:
        print("\nudp开始")
        recv_data = udp_socket.recvfrom(1024)
        print("收到数据:"+recv_data[0].decode('gbk'))
        print(recv_data[1])
        sleep(1)
        rate=recv_data[0].decode('gbk')
        print(rate)
        print("udp结束\n")
      except:
        print("err")


    # 3.关闭套接字
    udp_socket.close()
    
def http(typr):
  global rate
  #global data
  HOST = ''   # Symbolic name, meaning all available interfaces
  PORT = 8000  # Arbitrary non-privileged port
  
  socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 避免出现端口占用的错误
  print ('Socket created')
  
  # Bind socket to local host and port
  try:
      socket_server.bind((HOST, PORT))
  except socket.error as msg:
      print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
      sys.exit()
  
  print ('Socket bind complete')
  
  # Start listening on socket
  socket_server.listen(10)
  print ('Socket now listening')
  
  # now keep talking with the client
  while 1:
      # wait to accept a connection - blocking call
      conn, addr = socket_server.accept()
      conn.setblocking(False)  # 非阻塞，接收数据需要try...except...
      print ('Connected with ' + addr[0] + ':' + str(addr[1]))
      # Receiving from client
      response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'+rate
      #rate+='1'

      # if '\r\n\r\n' in data:  # 如果是POST方法，还要继续接收数据；如果含有图片，会更麻烦
      #   break
      try:
        rate += conn.recv(1024)
      except:
        pass
  
      print ('接收的数据->start')
      print (rate)
      print ('接收的数据->end')
      print ('向客户端发送数据：'+response)

      conn.sendall(response.encode())
      print ('发送完毕，关闭该连接')
      conn.close()  
  
  
  socket_server.close()

def main():
    t1 = threading.Thread(target=udp,args=(rate,))
    t2 = threading.Thread(target=http,args=(rate,))
    t1.start()
    time.sleep(1)
    t2.start()
    time.sleep(1)
    #print(data)

if __name__ == '__main__':
    main()
